#include "PreComplied.h"
#include "Exchange.h"

namespace Exchange
{

void PrintTab(lua_State* L)
{
	int tabPos = lua_gettop(L);
	lua_pushnil(L);
	while(lua_next(L, tabPos))
	{
		LuaInfo("key = %s \t", lua_tostring(L, -2));
		LuaInfo("val type = %s\n", lua_typename(L, lua_type(L, -1)));
		lua_pop(L, 1);
	}
}

int AccessBase(lua_State* L)
{
	int top = lua_gettop(L);
	const char* index = lua_tostring(L, 2);
	lua_getmetatable(L, 1);

	{
		lua_getfield(L, -1, "__self");
		//PrintTab(L);
		lua_pushvalue(L, 2);
		lua_gettable(L, -2);
		if(!lua_isnil(L, -1))
		{
			top = lua_gettop(L);
			lua_remove(L, -2);
			lua_remove(L, -2);
			top = lua_gettop(L);
			return 1;
		}
		else
			lua_pop(L, 2);
	}

	{
		lua_getfield(L, -1, "__base");
		//PrintTab(L);
		lua_pushvalue(L, 2);
		lua_gettable(L, -2);
		if(!lua_isnil(L, -1))
		{
			top = lua_gettop(L);
			lua_remove(L, -2);
			lua_remove(L, -2);
			top = lua_gettop(L);
			return 1;
		}
		else
			lua_pop(L, 3);
	}
	return 0;
}

static void call_stack(lua_State* L, int n)
{
    lua_Debug ar;
    if(lua_getstack(L, n, &ar) == 1)
	{
		lua_getinfo(L, "nSlu", &ar);

		if(n == 0)
			LuaInfo("Current call stack is:");
		if(ar.name)
			LuaInfo("%s() : line %d [%s : line %d]", ar.name, ar.currentline, ar.source, ar.linedefined);
		else
			LuaInfo("unknown : line %d [%s : line %d]", ar.currentline, ar.source, ar.linedefined);

		call_stack(L, n+1);
	}
}

int OnError(lua_State* L)
{
	LuaInfo("%s\n", lua_tostring(L, -1));
	//call_stack(L, 0);
	return 0;
}

}
